<?php
namespace Backend\Model;
use Think\Model;

class CodeModel extends Model
{

    // 定义表单验证的规则
    protected $_validate = array(
        //array('media_id', 'require', '必须要选择一个主分类！', 1),
        array('code_name', 'require', '分组名称不能为空！', 1),
        array('code_name', '', '代码位名称已存在！', 0, 'unique', 3),
        array('media_id', 'require', '媒体名称不能为空！', 1),
        array('width', 'require', '代码位尺寸不能为空！', 1),
        array('height', 'require', '代码位尺寸不能为空！', 1),
        array('width', 'number', '代码位尺寸必须是数字！', 1),
        array('height', 'number', '代码位尺寸必须是数字！', 1),

    );


    public function get_code($pageSize = 10) {

        $where = array('user_id' =>$_SESSION['id']);
        $count = $this->alias('a')->where($where)->count();
        $page = new \Think\Page($count, $pageSize);
        // 配置翻页的样式
        $page->setConfig('prev', '上一页');
        $page->setConfig('next', '下一页');
        $data['page'] = $page->show();
        /************************************** 取数据 ******************************************/

        $data['data'] = $this->alias('a')
            ->field('a.id,a.code_name,a.tag,a.rtbcomplement,a.update_time,a.status,a.width,a.height,a.flow_type,a.media_id,b.name')
            ->where($where)
            ->join('left join dsp_media b on a.media_id=b.id')
            ->order('a.id desc')
            ->limit($page->firstRow.','.$page->listRows)
            ->select();
        return $data;
    }

    public function get_code_info($where = [], $field = '') {
        if(!empty($where) && is_array($where)) {
            return $this->where($where)->field($field)->select();
        } else {
            return $this->select();
        }
    }


    // 添加前
    protected function _before_insert(&$data) {
        $data['update_time']=time();
        $data['user_id'] =$_SESSION['id'];
    }

    // 修改前
    protected function _before_update(&$data) {
        $data['update_time']=time();
    }
}
